<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 得到连续 K 个 1 的最少相邻交换次数 -->
    <script>
      var minMoves = function (nums, k) {
        let g = []
        let sum = []
        sum.push(0)
        for (let i = 0; i < nums.length; i++) {
          if (nums[i] === 1) {
            g.push(i - g.length)
            sum.push(sum[sum.length - 1] + g[g.length - 1])
          }
        }
        let m = g.length
        let res = Number.MAX_VALUE
        for (let i = 0; i <= m - k; i++) {
          let mid = i + Math.floor(k / 2)
          let r = g[mid]
          res = Math.min(res, (1 - (k % 2)) * r + (sum[i + k] - sum[mid + 1]) - (sum[mid] - sum[i]))
        }
        return res
      }
      console.log(minMoves([1, 0, 0, 1, 0, 1], 2))
    </script>
  </body>
</html>
